package com.example.getlrc;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
//Log.d("getlrc", "right");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String lrcFile = readLrcFile("/mnt/sdcard/Music/林俊杰 - 起风了（Live）.lrc");

    }

    @SuppressLint("NewApi")
    public String readLrcFile(String path) {//读取整个lrc文件的内容
        if (!path.contains(".lrc")) return null;//如果不是lrc文件就返回空
        File file = new File(path);//文件对象
        if (!file.exists())  return null;//没有该文件返回空
        FileInputStream fileInputStream = null;//输入流
        BufferedInputStream bufferedInputStream = null;//缓存输入流
        BufferedReader bufferedReader;//用来读取每一行数据
        StringBuilder lrcString = new StringBuilder();//
        try {
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);//ctrl+p出现参数提示
            bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream, StandardCharsets.UTF_8));
            String stringline = bufferedReader.readLine();//读取一行
            while (stringline != null) {
                lrcString.append(stringline).append("\n");//lrcString后面加上一行的内容，再加上换行符
                stringline = bufferedReader.readLine();//读取一行
            }
        } catch (IOException e) {
            return null;//发生错误返回空
        } finally {//资源回收
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                    if (bufferedInputStream != null) bufferedInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return lrcString.toString();
    }

    public class LrcBean {//用来储存一行歌词的信息的类

        private long mStart;//开始时间
        private long mEnd;//结束时间
        private String mLrc;//歌词

        public LrcBean(String lrc, long start, long end) {
            mLrc = lrc;
            mStart = start;
            mEnd = end;
        }

        public String getLrc() {
            return mLrc;
        }

        public long getStart() {
            return  mStart;
        }

        public long getEnd() {
            return mEnd;
        }

        public void setEnd(long end) {
            mEnd = end;
        }

    }

    public List<LrcBean> getLrc(String lrcFile) {//通过整个lrc文件解析返回LrcBean(用来储存一行歌词的信息的类)的List
        if (lrcFile == null) return null;
        List<LrcBean> list = new ArrayList<>();
        //1.更替转义字符
        String lrcText = lrcFile.replaceAll("&#58;", ":")
                .replaceAll("&#10;", "\n")
                .replaceAll("&#46;", ".")
                .replaceAll("&#32;", " ")
                .replaceAll("&#45;", "-")
                .replaceAll("&#13;", "\r")
                .replaceAll("&#39;", "'")
                .replaceAll("&nbsp;", " ")
                .replaceAll("&apos;", "'")
                .replaceAll("&&", "/")
                .replaceAll("\\|", "/");

        //Toast.makeText(MainActivity.this, lrcText, Toast.LENGTH_SHORT).show();
        //更替转义字符后，将字符串转换成字符串数组，区分每个字符串的边界是\n
        String[] split = lrcText.split("\n");
        //逐行解析
        for (int i = 0; i < split.length; i++) {
            String line = split[i];
            //这一行为空或一个空格就跳过
            if (line.equals(" ") || line.isEmpty()) continue;
            //歌曲信息及时间偏移也跳过
            if (line.contains("[ti:") || line.contains("[ar:") || line.contains("[al:")
                    || line.contains("[by:") || line.contains("[offset:")) continue;
            //截取歌词部分
            String lrc = line.substring(line.indexOf("]") + 1);
            //歌词为空或一个空格跳过
            if (lrc.equals(" ") || lrc.isEmpty() || lrc.equals("\\")) continue;
            //获取时间信息
            String min = line.substring(line.indexOf("[") + 1, line.indexOf("[") + 3);
            String seconds = line.substring(line.indexOf(":") + 1, line.indexOf(":") + 3);
            String mills = line.substring(line.indexOf(".") + 1, line.indexOf(".") + 3);
            long startTime = Long.valueOf(min) * 60 * 1000 +
                    Long.valueOf(seconds) * 1000 + Long.valueOf(mills) * 10;
            //结束时间默认为开始+10秒
            LrcBean lrcBean = new LrcBean(lrc, startTime, startTime + 10000);
            list.add(lrcBean);
            //从第二个开始，把这一个LrcBean的开始时间设为上一个LrcBean的结束时间（这样显然不能设置到最后一个LrcBean）
            if (list.size() > 1) list.get(list.size() - 2).setEnd(startTime);
        }
        return list;//返回歌词信息List
    }

    //读取某个文件夹下的所有文件
    private void init(String path) {
        Toast.makeText(MainActivity.this,"init", Toast.LENGTH_SHORT).show();
        File file = new File(path);
        if (file.isDirectory()) {//判断是否是文件夹
            File [] fileArray = file.listFiles();
            if(null != fileArray && 0 != fileArray.length) {
                for(int i = 0; i < fileArray.length; i++) {
                    Toast.makeText(MainActivity.this,"" + fileArray[i].getName(), Toast.LENGTH_SHORT).show();
                    // fileArray[i].getName();
                }
            }
        } else {
            //路径不是文件夹
        }
    }
}